#coding=utf-8
import traceback
from flask import Flask, request, jsonify
import time
from selenium.webdriver.common.by import By
from seleniumwire import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from webdriver_manager.microsoft import EdgeChromiumDriverManager

app = Flask(__name__)

@app.route('/getXtoken', methods=['GET'])
def getXtoken():
    #获取传来的用户名喝密码
    username = request.args.get('userName')
    password = request.args.get('pwd')
    print("捕获到请求")
    options = webdriver.EdgeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    driver = webdriver.Edge(service=EdgeService(EdgeChromiumDriverManager().install()), options=options)
    print("创建edge")
    # 清除所有cookies
    driver.delete_all_cookies()
    firstUrl = 'https://authserver.sandau.edu.cn/authserver/login?service=https%3A%2F%2Fcas.sandau.edu.cn%2Fcas%2Flogin%3Fservice%3Dhttps%253A%252F%252Fsuperapp.sandau.edu.cn%252Fpages%252Ftab%252Findex%252Findex'
    # 打开网页
    driver.get(firstUrl)

    print("打开网页")

    try:
        # 输入用户名称
        username_field = driver.find_element(By.ID, "username")
        username_field.send_keys(username)
        # 输入密码
        password_field = driver.find_element(By.ID, "password")
        password_field.send_keys(password)

        driver.find_element(By.ID, "login_submit").click()
        time.sleep(5)
        # 直接获取cookie中的xtoken
        x_id_token = driver.execute_script("return localStorage.getItem('idToken');")
    except Exception:
        traceback.print_exc()
        driver.quit()
        print("关闭浏览器")

    # 关闭浏览器
    driver.quit()
    print("关闭浏览器")
    response = {
        'state': 200,
        'x_id_token': x_id_token,
        # 'user_id': user_id,
        # 'nickName': nickName
    }
    # Return the JSON response
    return jsonify(response)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8899)
